Please help to find mistakes in my code:
function multipleOfIndex(array) {
return array.forEach( item => console.log(item%array.indexOf(item) === 0) )
}
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false
obviously, I was expecting
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, true
Thanks!
The problem is relying on indexOf when more than one value is the same in the array - array.indexOf(10) is always 4, see the extended log here:
function multipleOfIndex(array) {
return array.forEach( item => console.log(item,array.indexOf(item),item%array.indexOf(item) === 0) )
}
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false
The solution is to use the forEach index parameter (2nd one)
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
function multipleOfIndex(array) {
return array.forEach( (item,idx) => console.log(item%idx === 0) )
}
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false
The [indexOf] method returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1. So the [indexOf] value of the last 10 is 4.